package com.example.capsule_chat0322.listener;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.capsule_chat0322.R;
import com.example.capsule_chat0322.activity.ChatActivity;
import com.example.capsule_chat0322.activity.OneToOneChatActivity;
import com.example.capsule_chat0322.adapter.FriendApplyAdapter;
import com.example.capsule_chat0322.adapter.FriendListAdapter;
import com.example.capsule_chat0322.adapter.FriendMoreFunctionAdapter;
import com.example.capsule_chat0322.adapter.MsgAdapter;
import com.example.capsule_chat0322.bean.FriendApplyBean;
import com.example.capsule_chat0322.bean.FunctionBean;
import com.example.capsule_chat0322.bean.GlobalRoomBean;
import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.bean.Msg;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.fragment.FriendListFragment;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.global.GlobalChatRoomMap;
import com.example.capsule_chat0322.global.GlobalThreadPool;
import com.example.capsule_chat0322.global.LRUCache;
import com.example.capsule_chat0322.interfaces.NettyMessageInterface;
import com.example.capsule_chat0322.request.UserInfoRequest;

import java.util.Base64;
import java.util.List;


/**
 * @Author: zhuzhiming
 * @Date: 2022/4/27 20:15
 */
public class NettyOneToOneMessageListener implements NettyMessageInterface {

    private boolean hasCache = false;


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void consumerMessage(MessageBean messageBean) {

        if (messageBean.getMsgType() == 7 && messageBean.getSenderId() != null && messageBean.getSenderId().equals(GlobalAssistMap.getObject("userId")))
            return;


        String senderId = messageBean.getSenderId();
        String position = (String) GlobalAssistMap.getObject(senderId + "position");
        FriendListAdapter adapter = null;
        View view = null;

        if (position != null) {
            RecyclerView friend_recycler_view = (RecyclerView) GlobalAssistMap.getObject("friendRecyclerView");
            view = friend_recycler_view.getChildAt(Integer.parseInt(position));
            adapter = (FriendListAdapter) GlobalAssistMap.getObject("friendListAdapter");
        }

        if (messageBean.getMsgType() == 10) {

            if (messageBean.getStatus() == 4) {
                newFriendListView(messageBean);
                return;
            }
            updateFriendApplyView(messageBean);
        }

        if (messageBean.getMsgType() == 9 && adapter != null) {
            adapter.updateFriendListView(view, messageBean, messageBean.getContent());
            return;
        }


        if (adapter != null && messageBean.getStatus() == 0 && messageBean.getSenderId() != null && !messageBean.getSenderId().equals(GlobalAssistMap.getObject("userId"))) {

            String content = "";
            switch (messageBean.getMsgType()) {
                case 0:
                    content = messageBean.getContent().length() > 10 ? messageBean.getContent().substring(0, 10) + "..." : messageBean.getContent();
                    break;
                case 1:
                    content = ("[图片]");
                    break;
                case 2:
                    content = ("[文件]");
                    break;
                case 3:
                    content = ("[视频]");
                    break;
                case 8:
                    content = "对方撤回了一条消息";
                    break;

                default:
                    content = ("");
            }

            adapter.updateFriendListView(view, messageBean, content);

        }

        GlobalRoomBean globalRoomBean = GlobalChatRoomMap.getRoomInfo(messageBean.getRoomName());
        OneToOneChatActivity activity = (OneToOneChatActivity) globalRoomBean.getActivity();

        if (messageBean.getMsgType() == 7) {
            // doChangeRoomPeopleCount(activity, messageBean.getPeopleChangeCount());
            List<Msg> msgList = globalRoomBean.getMsgList();
            String str = messageBean.getPeopleChangeCount() + "|" + messageBean.getSenderName();
            Msg receiveMsg = new Msg(messageBean.getSenderId(), messageBean.getRoomName(), Msg.WORD_TYPE, str, Msg.TYPE_REMIND, "", true);
            updateMessageList(msgList, receiveMsg, globalRoomBean, activity, messageBean);
            //return;
        }

        if (messageBean.getSenderId().equals(GlobalAssistMap.getObject("userId"))) {
            int msgId = messageBean.getLocalMsdId();
            Msg cacheMsg = (Msg) GlobalAssistMap.getObject(msgId + "msg");
            cacheMsg.setId(messageBean.getMsgId());
            GlobalAssistMap.removeObject(msgId + "msg");
            return;
        }


        if (messageBean.getStatus() == 1) {


            MessageBean finalMessageBean = messageBean;

            final UserInfoBean[] userInfoBean = {(UserInfoBean) GlobalAssistMap.getObject(senderId + "Info")};
            if (userInfoBean[0] == null) {
                UserInfoRequest.doGetUserInfoRequest(new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(@NonNull Message message) {
                        userInfoBean[0] = (UserInfoBean) message.obj;
                        if (userInfoBean[0] != null) {
                            GlobalAssistMap.putObject(senderId + "Info", userInfoBean[0]);
                        }
                        return true;
                    }
                }), senderId);
            }

            OneToOneChatActivity finalActivity = activity;
            GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                @Override
                public void run() {

                    finalActivity.runOnUiThread(new Runnable() {
                        @RequiresApi(api = Build.VERSION_CODES.O)
                        @Override
                        public void run() {
                            List<Msg> msgList = globalRoomBean.getMsgList();
                            final String[] senderAvatarPath = {(String) GlobalAssistMap.getObject(messageBean.getSenderId() + "Avatar")};
                            if ((senderAvatarPath[0] == null || senderAvatarPath[0].equals("")) && !messageBean.getSenderAvatarPath().contains("/")) {
                                senderAvatarPath[0] = messageBean.getSenderAvatarPath();
                                GlobalAssistMap.putObject((finalMessageBean.getSenderId() + "Avatar"), messageBean.getSenderAvatarPath());
                            }
                            if ((senderAvatarPath[0] == null || senderAvatarPath[0].equals("")) && messageBean.getSenderAvatarPath().contains("/")) {

                                LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                Bitmap bitmap = (Bitmap) lruCache.get(messageBean.getSenderAvatarPath().substring(messageBean.getSenderAvatarPath().lastIndexOf("/")));
                                // Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(messageBean.getSenderAvatarPath().substring(messageBean.getSenderAvatarPath().lastIndexOf("/")));
                                if (bitmap == null) {
                                    hasCache = false;
                                    Handler handler = new Handler(new Handler.Callback() {
                                        @Override
                                        public boolean handleMessage(@NonNull Message message) {

                                            UserInfoBean userInfoBean = (UserInfoBean) message.obj;
                                            if (userInfoBean != null) {
                                                if (userInfoBean.getAvatarServerPath() != null && !userInfoBean.getAvatarServerPath().equals("")) {
                                                    senderAvatarPath[0] = Constant.IMAGE_PATH + userInfoBean.getAvatarServerPath().substring(userInfoBean.getAvatarServerPath().lastIndexOf("/") + 1);
                                                    Bitmap bitmap = BitmapFactory.decodeFile(senderAvatarPath[0]);
                                                    if (bitmap == null) {
                                                        UserInfoRequest.getAvatar(new Handler(new Handler.Callback() {
                                                            @Override
                                                            public boolean handleMessage(@NonNull Message message) {
                                                                GlobalAssistMap.putObject(finalMessageBean.getSenderId() + "Avatar", senderAvatarPath[0]);
                                                                return true;
                                                            }
                                                        }), userInfoBean.getAvatarServerPath());
                                                    }
                                                } else {
                                                    senderAvatarPath[0] = userInfoBean.getAvatarUrl();
                                                }

                                                Msg receiveMsg = null;

                                                if (finalMessageBean.getMsgType() == Msg.WORD_TYPE) {
                                                    receiveMsg = new Msg(finalMessageBean.getSenderId(), finalMessageBean.getRoomName(), Msg.WORD_TYPE, finalMessageBean.getContent(), Msg.TYPE_RECEIVE, senderAvatarPath[0], true);
                                                    updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                                } else {

                                                    if (finalMessageBean.getMsgType() == 1) {

                                                        LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                                        Bitmap bitmap = (Bitmap) lruCache.get(finalMessageBean.getFileName());
                                                        // Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(finalMessageBean.getFileName());
                                                        if (bitmap == null) {
                                                            byte[] by = Base64.getDecoder().decode(finalMessageBean.getContent());
                                                            bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                                                            if (bitmap != null) {
                                                                lruCache.put(finalMessageBean.getFileName(), bitmap);
                                                                // GlobalAssistMap.putObject(finalMessageBean.getFileName(), bitmap);
                                                            }
                                                            by = null;
                                                        }
                                                        receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, finalMessageBean.getFileName(), finalMessageBean.getRoomName(), senderAvatarPath[0], null, true);
                                                        updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                                    } else if (finalMessageBean.getMsgType() == 2) {
                                                        receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, Constant.FILE_SERVER_PATH + messageBean.getFileName(), finalMessageBean.getRoomName(), senderAvatarPath[0], finalMessageBean.getFileName() + " " + finalMessageBean.getFileSize(), true);
                                                        updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                                    } else if (finalMessageBean.getMsgType() == 3) {

                                                        String cacheKey = finalMessageBean.getFileName();
                                                        LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                                        Bitmap bitmap = (Bitmap) lruCache.get(cacheKey);
                                                        if (bitmap == null) {
                                                            byte[] by = Base64.getDecoder().decode(finalMessageBean.getContent());
                                                            bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                                                            if (bitmap != null) {
                                                                lruCache.put(finalMessageBean.getFileName(), bitmap);
                                                                //GlobalAssistMap.putObject(finalMessageBean.getFileName(), bitmap);
                                                            }
                                                            by = null;
                                                        }

                                                        receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, Constant.VIDEO_SERVER_PATH + finalMessageBean.getFileName(), finalMessageBean.getRoomName(), senderAvatarPath[0], ".mp4 ", true);
                                                        updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);

                                                    } else if (messageBean.getMsgType() == 8) {

                                                        int msgId = messageBean.getMsg().getId();
                                                        for (int i = 0; i < msgList.size(); i++) {
                                                            if (msgList.get(i).getId() == msgId) {
                                                                Msg newMsg = new Msg(finalMessageBean.getSenderId(), messageBean.getRoomName(), Msg.RECALL_TYPE, null, Msg.TYPE_RECEIVE, senderAvatarPath[0], true);
                                                                msgList.remove(i);
                                                                msgList.add(i, newMsg);
                                                                break;
                                                            }
                                                        }

                                                        String str = "" + "|" + messageBean.getSenderName();
                                                        Msg remindMsg = new Msg(messageBean.getSenderId(), messageBean.getRoomName(), Msg.WORD_TYPE, str, Msg.TYPE_REMIND, "", true);
                                                        updateMessageList(msgList, remindMsg, globalRoomBean, activity, messageBean);

                                                    }
                                                }

                                            }
                                            return true;
                                        }
                                    });

                                    UserInfoRequest.doGetUserInfoRequest(handler, finalMessageBean.getSenderId());
                                } else {
                                    hasCache = true;
                                }

                            } else if (hasCache || !messageBean.getSenderAvatarPath().contains("/") || (senderAvatarPath[0] != null && !senderAvatarPath[0].equals(""))) {
                                Msg receiveMsg = null;
                                String avatarPath = hasCache ? (String) GlobalAssistMap.getObject(messageBean.getSenderAvatarPath().substring(messageBean.getSenderAvatarPath().lastIndexOf("/"))) : ((senderAvatarPath[0] == null || senderAvatarPath[0].equals("")) ? messageBean.getSenderAvatarPath() : senderAvatarPath[0]);
                                if (finalMessageBean.getMsgType() == Msg.WORD_TYPE) {
                                    receiveMsg = new Msg(finalMessageBean.getSenderId(), finalMessageBean.getRoomName(), Msg.WORD_TYPE, finalMessageBean.getContent(), Msg.TYPE_RECEIVE, avatarPath, true);
                                    updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                } else {

                                    if (finalMessageBean.getMsgType() == 1) {
                                        LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                        Bitmap bitmap = (Bitmap) lruCache.get(finalMessageBean.getFileName());
                                        // Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(finalMessageBean.getFileName());
                                        if (bitmap == null) {
                                            byte[] by = Base64.getDecoder().decode(finalMessageBean.getContent());
                                            bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                                            if (bitmap != null) {
                                                lruCache.put(finalMessageBean.getFileName(), bitmap);
                                                // GlobalAssistMap.putObject(finalMessageBean.getFileName(), bitmap);
                                            }
                                            by = null;
                                        }
                                        receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, finalMessageBean.getFileName(), finalMessageBean.getRoomName(), avatarPath, null, true);
                                        updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                    } else if (finalMessageBean.getMsgType() == 2) {
                                        receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, Constant.FILE_SERVER_PATH + messageBean.getFileName(), finalMessageBean.getRoomName(), avatarPath, finalMessageBean.getFileName() + " " + finalMessageBean.getFileSize(), true);
                                        updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);
                                    } else if (finalMessageBean.getMsgType() == 3) {
                                        LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                                        String cacheKey = finalMessageBean.getFileName();
                                        Bitmap bitmap = (Bitmap) lruCache.get(cacheKey);
                                        //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(cacheKey);
                                        if (bitmap == null) {
                                            byte[] by = Base64.getDecoder().decode(finalMessageBean.getContent());
                                            bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                                            if (bitmap != null) {
                                                lruCache.put(finalMessageBean.getFileName(), bitmap);
                                                // GlobalAssistMap.putObject(finalMessageBean.getFileName(), bitmap);
                                            }
                                            by = null;
                                        }

                                        receiveMsg = new Msg(finalMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, Constant.VIDEO_SERVER_PATH + finalMessageBean.getFileName(), finalMessageBean.getRoomName(), senderAvatarPath[0], ".mp4 ", true);
                                        updateMessageList(msgList, receiveMsg, globalRoomBean, finalActivity, finalMessageBean);

                                    } else if (messageBean.getMsgType() == 8) {

                                        int msgId = messageBean.getMsg().getId();
                                        for (int i = 0; i < msgList.size(); i++) {
                                            if (msgList.get(i).getId() == msgId) {
                                                Msg newMsg = new Msg(finalMessageBean.getSenderId(), messageBean.getRoomName(), Msg.RECALL_TYPE, null, Msg.TYPE_RECEIVE, senderAvatarPath[0], true);
                                                msgList.remove(i);
                                                msgList.add(i, newMsg);
                                                break;
                                            }
                                        }

                                        String str = "" + "|" + messageBean.getSenderName();
                                        Msg remindMsg = new Msg(messageBean.getSenderId(), messageBean.getRoomName(), Msg.WORD_TYPE, str, Msg.TYPE_REMIND, "", true);
                                        updateMessageList(msgList, remindMsg, globalRoomBean, activity, messageBean);

                                    }

                                }

                            }
                        }
                    });
                }
            });


        }


    }

    private void newFriendListView(MessageBean messageBean) {
        FriendListAdapter friendListAdapter = (FriendListAdapter) GlobalAssistMap.getObject("friendListAdapter");

        RecyclerView friendRecyclerView = (RecyclerView) GlobalAssistMap.getObject("friendRecyclerView");
        FriendListFragment friendListFragment = (FriendListFragment) GlobalAssistMap.getObject("friendListFragment");

        friendListFragment.getActivity().runOnUiThread(() -> {

            UserInfoRequest.doGetUserInfoRequest(new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(@NonNull Message message) {

                    UserInfoBean userInfoBean = (UserInfoBean) GlobalAssistMap.getObject(messageBean.getSenderId() + "Info");
                    userInfoBean.setLastMessage("你们已经是好友了~");
                    userInfoBean.setNewMessageCount(-1);
                    friendListAdapter.friendBeanList.add(userInfoBean);
                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(friendListFragment.getContext());
                    friendRecyclerView.setAdapter(friendListAdapter);
                    friendRecyclerView.setLayoutManager(linearLayoutManager);
                    friendListFragment.adapterAddListener(friendListAdapter);

                    return true;
                }
            }), messageBean.getSenderId());
        });
    }

    private void updateFriendApplyView(MessageBean messageBean) {

        ImageView remind = (ImageView) GlobalAssistMap.getObject("remind");
        remind.post(new Runnable() {
            @Override
            public void run() {
                remind.setVisibility(View.VISIBLE);
            }
        });


        FriendMoreFunctionAdapter friendMoreFunctionAdapter = (FriendMoreFunctionAdapter) GlobalAssistMap.getObject("friendMoreFunctionAdapter");
        List<FriendApplyBean> applyList = (List<FriendApplyBean>) GlobalAssistMap.getObject("applyList");
        FriendApplyBean friendApplyBean = new FriendApplyBean();
        friendApplyBean.setApplyId(messageBean.getSenderId());
        friendApplyBean.setApplyInstruction(messageBean.getContent());
        friendApplyBean.setFriendAvatarPath(messageBean.getSenderAvatarPath());
        applyList.add(friendApplyBean);
        GlobalAssistMap.putObject("friendApplyAdapter", new FriendApplyAdapter(applyList));

        RecyclerView friendFunctionRecyclerView = (RecyclerView) GlobalAssistMap.getObject("friendFunctionRecyclerView");
        if (friendFunctionRecyclerView == null) {
            return;
        }


        int index = 0;
        for (int i = 0; i < friendMoreFunctionAdapter.functionBeanList.size(); i++) {

            if (friendMoreFunctionAdapter.functionBeanList.get(i).getFunctionName().equals("好友申请")) {
                friendMoreFunctionAdapter.functionBeanList.get(i).setApplyList(applyList);
                friendMoreFunctionAdapter.functionBeanList.get(i).setApplyListStatus(null);
                index = i;
                break;
            }
        }

        View functionView = friendFunctionRecyclerView.getChildAt(index);
        TextView friendApply = functionView.findViewById(R.id.message_count);
        friendApply.post(new Runnable() {
            @Override
            public void run() {
                friendApply.setVisibility(View.VISIBLE);
                String friendApplyCount = friendApply.getText().toString();
                if (friendApplyCount.equals("")) {
                    friendApplyCount = "1";
                } else {
                    int count = Integer.parseInt(friendApplyCount);
                    if (count > 99) {
                        friendApplyCount = "99+";
                    } else {
                        friendApplyCount = String.valueOf(count + 1);
                    }
                }
                friendApply.setText(friendApplyCount);
            }
        });
    }


    private void updateMessageList(List<Msg> msgList, Msg receiveMsg, GlobalRoomBean globalRoomBean, Activity activity, MessageBean finalMessageBean) {
        receiveMsg.setId(finalMessageBean.getMsgId());
        msgList.add(receiveMsg);
        globalRoomBean.setMsgList(msgList);
        MsgAdapter adapter = new MsgAdapter(msgList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        RecyclerView msgRecyclerView = globalRoomBean.getMsgRecyclerView();
        msgRecyclerView.setLayoutManager(layoutManager);
        msgRecyclerView.setAdapter(adapter);
        adapter.notifyItemInserted(msgList.size() - 1);//当有新消息是刷新RecyclerView中的显示
        msgRecyclerView.scrollToPosition(msgList.size() - 1);//将RecyclerView定位在最后一行
        globalRoomBean.setActivity(activity);
        globalRoomBean.setRoomName(finalMessageBean.getRoomName());
        globalRoomBean.setMsgRecyclerView(msgRecyclerView);
        globalRoomBean.setMsgList(msgList);
        globalRoomBean.setAdapter(adapter);
        GlobalChatRoomMap.putRoomInfo(finalMessageBean.getRoomName(), globalRoomBean);
    }

    @Override
    public void dealInactive() {
    }

    private void doChangeRoomPeopleCount(ChatActivity activity, int count) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                activity.updatePeopleCount(count);
            }
        });

    }
}
